import NavBar from '@/components/NavBar'
import {
  getUserProfile,
  updateAvatar,
  updateProfile,
} from '@/store/actions/profile'
import { List, Calendar, Popup, Toast, Modal } from 'antd-mobile'
import { useEffect, useState, useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import styles from './index.module.scss'
import EditInput from './components/EditInput'
import classNames from 'classnames'
import EditList from './components/EditList'
import dayjs from 'dayjs'
import { logout } from '@/store/actions/login'

const ProfileEdit = () => {
  const fileRef = useRef()

  const config = {
    avatar: [
      {
        title: '拍照',
        onClick: () => {
          fileRef.current.click()
        },
      },
      {
        title: '本地选择',
        onClick: () => {
          fileRef.current.click()
        },
      },
    ],
    gender: [
      {
        title: '男',
        onClick: () => {
          onFormCommit('gender', 0)
          Toast.show({
            icon: 'success',
            content: '修改成功',
          })
        },
      },
      {
        title: '女',
        onClick: () => {
          onFormCommit('gender', 1)
          Toast.show({
            icon: 'success',
            content: '修改成功',
          })
        },
      },
    ],
  }
  const onAvatarChange = (e) => {
    // 获取选中的图片文件
    const file = e.target.files[0]

    // 生成表单数据
    const formData = new FormData()
    formData.append('photo', file)

    // 调用 Action 进行上传和 Redux 数据更新
    dispatch(updateAvatar(formData))

    Toast.show({
      icon: 'success',
      content: '头像上传成功',
    })
    onClose()
  }
  const navigate = useNavigate()
  const [dayLoading, setdayLoading] = useState(false)
  const dispatch = useDispatch()
  const [visible4, setVisible4] = useState({
    // 抽屉显示状态
    visible: false,
    // 显示的类型
    type: '',
  })

  // 修改时间
  const updateDay = async (e) => {
    const day = dayjs(e).format('YYYY-MM-DD')
    // console.log(dayjs(e).format('YYYY-MM-DD'))
    await dispatch(updateProfile('birthday', day))
    Toast.show({
      icon: 'success',
      content: '修改生日成功',
    })
    setdayLoading(false)
  }

  // 控制头像和性别
  const [visible3, setVisible3] = useState({
    // 抽屉显示状态
    visible: false,
    // 显示的类型
    type: '',
  })

  const profile = useSelector((state) => state.profile.userProfile)
  const onClose = () => {
    setVisible4({
      visible: false,
      type: '',
    })
    setVisible3({
      visible: false,
      type: '',
    })
  }
  // 抽屉表单的数据提交
  const onFormCommit = (name, value) => {
    // 调用 Action 更新数据
    dispatch(updateProfile(name, value))
    // 关闭抽屉
    setVisible4({
      visible: false,
      type: '',
    })
    setVisible3({
      visible: false,
      type: '',
    })
  }
  // 退出登录
  const onLogout = () => {
    // 弹出确认对话框
    // Modal.alert('温馨提示', '你确定退出吗？', [
    //   // 取消按钮
    //   { text: '取消' },
    //   // 确认按钮
    //   {
    //     text: '确认',
    //     style: { color: '#FC6627' },
    //     onPress: () => {
    //       console.log('执行登出....')
    //     },
    //   },
    // ])
    Modal.confirm({
      title: '温馨提示',
      content: '你确定退出吗？',
      onConfirm: async () => {
        dispatch(logout())

        navigate('/login')
        Toast.show({
          icon: 'success',
          content: '退出成功',
        })
      },
    })
  }

  useEffect(() => {
    dispatch(getUserProfile())
  }, [dispatch])
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar onLeftClick={() => navigate(-1)}>个人信息</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              arrow
              onClick={() =>
                setVisible3({
                  visible: true,
                  type: 'avatar',
                })
              }
              extra={
                <span className="avatar-wrapper">
                  <img src={profile.photo} alt="" />
                </span>
              }
            >
              头像
            </List.Item>

            <List.Item
              arrow
              extra={profile.name}
              onClick={() =>
                setVisible4({
                  visible: true,
                  type: 'name',
                })
              }
            >
              昵称
            </List.Item>

            <List.Item
              onClick={() =>
                setVisible4({
                  visible: true,
                  type: 'intro',
                })
              }
              arrow
              extra={
                <span
                  className={classNames('intro', profile.intro ? 'normal' : '')}
                >
                  {profile.intro || '未填写'}
                </span>
              }
            >
              简介
            </List.Item>
          </List>

          {/* 列表二：显示性别、生日 */}
          <List className="profile-list">
            <List.Item
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
              onClick={() =>
                setVisible3({
                  visible: true,
                  type: 'gender',
                })
              }
            >
              性别
            </List.Item>
            <List.Item
              arrow
              extra={profile.birthday}
              onClick={() => setdayLoading(!dayLoading)}
            >
              生日
            </List.Item>
          </List>

          <Calendar
            className={dayLoading ? '' : 'day'}
            selectionMode="single"
            defaultValue={profile.birthday}
            min={new Date(1900, 1, 1, 0, 0, 0)}
            max={new Date()}
            onChange={updateDay}
          />

          {/* 文件选择框，用于头像图片的上传 */}
          <input
            type="file"
            hidden
            ref={fileRef}
            style={{ display: 'none' }}
            onChange={onAvatarChange}
          />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={onLogout}>
            退出登录
          </button>
        </div>
      </div>
      <Popup
        visible={visible4.visible}
        position="right"
        bodyStyle={{ width: '100vw' }}
      >
        <EditInput
          onClose={onClose}
          type={visible4.type}
          profile={profile}
          onCommit={onFormCommit}
        />
      </Popup>
      <Popup
        visible={visible3.visible}
        position="bottom"
        onMaskClick={onClose}
        bodyStyle={{
          width: '100vw',
          height: '45vw',
        }}
      >
        <EditList config={config} type={visible3.type} onClose={onClose} />{' '}
      </Popup>
    </div>
  )
}

export default ProfileEdit
